package com.butterfly.hotkey.client.core.collector;


import com.butterfly.hotkey.client.core.collector.segment.AbstractSegment;
import com.butterfly.hotkey.core.model.HotKeyModel;
import com.google.common.collect.Lists;

import java.util.Collection;
import java.util.Map;

import static com.butterfly.hotkey.core.constant.NumConst.ONE;

/**
 * Key数量统计,时效性要求高，用于hotkey的探测
 * 1. 定时上报给worker
 * 2. worker进行计算，如果是hotkey，推送给client已经是hotkey
 * 3. client将数据缓存
 * 4. dashboard将hot key进行保存，用于统计
 * <p>
 * 双buffer设计
 *
 * @author butterfly
 * @since 2024/10/30
 */
public class DefaultKeyAccessCollector extends AbstractSegmentCollector<HotKeyModel, HotKeyModel, HotKeyModel> {

    public DefaultKeyAccessCollector() {
        segments = new Segment[]{new Segment(), new Segment()};
    }

    @Override
    protected Collection<HotKeyModel> convertSegment(Map<String, HotKeyModel> segmentMap) {
        return Lists.newArrayList(segmentMap.values());
    }

    private static class Segment extends AbstractSegment<HotKeyModel, HotKeyModel> {

        @Override
        public void addKey(HotKeyModel hotKeyModel) {
            String key = hotKeyModel.getKey();
            HotKeyModel existKey = segment.putIfAbsent(key, hotKeyModel);
            if (existKey != null) {
                existKey.addCount(ONE);
            }
        }
    }

}
